package com.guan.order.service;

import com.guan.order.mapper.OrderMapper;
import com.guan.order.model.OrderInfo;
import com.guan.product.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    private static List<ServiceInstance> instances;

    @PostConstruct
    public void init() {
        //根据应⽤名称获取服务列表
        instances = discoveryClient.getInstances("product-service");
    }

    public OrderInfo selectOrderByID(Integer orderID) {
        OrderInfo orderInfo = orderMapper.selectOrderById(orderID);
        // 从Eureka获取服务列表
        /*List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        //有多个服务，根据轮询获取
        int index = atomicInteger.getAndIncrement() % instances.size();
        String uri = instances.get(index).getUri().toString();
        String url = uri + "/product/" + orderInfo.getProductId();
        log.info("远程调用url：{}", url);*/
        String url = "http://product-service/product/"+ orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}
